<template>
    <el-container class="in_bill_form_container">
        <el-main>
            <el-card class="box-card">
                <div slot="header" class="clearfix" style="padding-left: 0;">
                    <el-form ref="stockInBillForm" :rules="rules" :model="formData" label-width="100px" v-enterToNext>
                        <el-row :gutter="15">
                            <el-col :span="8">
                                <el-form-item label="入库单号" prop="code">
                                    <el-input v-model="formData.code" clearable :disabled="!isEditFlag" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="入库类型" prop="in_type">
                                    <el-select v-model="formData.in_type" :disabled="!(isEditFlag && !isGenBill)"
                                               placeholder="请选择入库类型" style="width: 100%" clearable>
                                        <el-option v-for="(item, index) in inTypeList"
                                                   :key="index" :label="item.label" :value="item.value" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="数据来源编号" prop="src_code" >
                                    <el-input v-model="formData.src_code"
                                              style="width: 100%;" clearable :disabled="!(isEditFlag && !isGenBill)">
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="客户" prop="client_sid">
                                    <vSelectBottom v-model="formData.client_sid" type="clientsDrawer"
                                                   @event="handleClientEvent" :options="clientOptions"
                                                   :disabled="!isEditFlag" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="供应商" prop="supplier_sid">
                                    <vSelectBottom v-model="formData.supplier_sid" type="supplierDrawer"
                                                   @event="handleSupplierEvent" :options="supplierOptions"
                                                   :disabled="!isEditFlag" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="入库日期" prop="in_date">
                                    <el-date-picker v-model="formData.in_date"
                                                    type="date" value-format="yyyy-MM-dd"
                                                    :disabled="!isEditFlag" style="width: 100%;" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="仓库" prop="warehouse_sid">
                                    <remote-select v-model="formData.warehouse_sid" :options="wareHouseProps"
                                                   style="width: 100%" :disabled="!isEditFlag"
                                                   @event="handleRemoteSelectEvent" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="入库数量" prop="in_qty">
                                    <el-input v-model="totalPositionQty" disabled />
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="备注" prop="note_info">
                                    <el-input type="textarea" v-model="formData.note_info"
                                              clearable maxlength="300" show-word-limit :disabled="!isEditFlag" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
                <div class="card_content">
                    <vxeTableTemplate :data="dataList" :options.sync="tableOptions" />
                </div>
            </el-card>
        </el-main>
    </el-container>
</template>

<script>
import { mapState } from "vuex";
import tableRender from "@common/components/common/tableRender";
import clothing from "@jxc/utils/clothing";
import '@jxc/components/vxeTable/ProductDownDialog';

export default {
    name: "StockInBillForm",
    props: {
        row: {
            type: Object,
            default: null,
        },
        detail: {
            type: Boolean,
            default: false,
        },
    },
    data() {
        let _this = this;
        return {
            rules: {
                code: [
                    { required: true, message: "请输入入库单号", trigger: "blur" },
                    { max: 32, message: "最大 32 位字符，内容过长，请删减", trigger: "blur", },
                ],
                in_type: [
                    { required: true, message: "请选择入库类型", trigger: "change" },
                ],
                in_date: [
                    { required: true, message: "请选择入库日期", trigger: "change" },
                ],
                warehouse_sid: [
                    { required: true, message: "请选择仓库", trigger: "change" },
                ],
            },
            clientOptions: {
                disabled: false,
                placeholder: '请选择客户',
                bottomAction: {
                    permission: 'save_sys_client',
                    permissionUrl: '/sysClients',
                },
            },
            supplierOptions: {
                disabled: false,
                placeholder: '请选择供应商',
                bottomAction: {
                    permission: 'save_sys_supplier',
                    permissionUrl: '/sysSupplier',
                },
            },
            formData: {},
            dataList: [],
            tableOptions: {
                ref: "JxcInBillDialogTable",
                container: ".in_bill_form_container",
                showSummary: true,
                summaryArray: [ 'in_qty', 'amount', 'position_in_qty' ],
                columns: [],
                baseColumns: [
                    {
                        label: "物料",
                        prop: "goods_name",
                        align: "center",
                        editRender: {
                            name: "vProductDownDialog",
                            type: 'buy',
                            events: { event: _this.handleGoodsEvent },
                        },
                    },
                    {
                        label: "规格",
                        prop: "spec_name",
                        align: "center",
                    },
                    {
                        label: "价格",
                        prop: "price",
                        align: "center",
                        width: 80,
                        editRender: {
                            name: 'CustomInput',
                            autoselect: true,
                            props: {
                                doubleInput: {
                                    len: 4,
                                    negative: false,
                                },
                            },
                            events: {
                                input: _this.rewriteChangeRow,
                            },
                            filter(row) {
                                return _this.$utils.isNotEmpty(row.product_sid);
                            },
                        },
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 4),
                    },
                    {
                        label: "数量",
                        prop: "in_qty",
                        align: "center",
                        width: 100,
                        editRender: {
                            name: 'CustomInput',
                            autoselect: true,
                            props: {
                                doubleInput: {
                                    len: 3,
                                    negative: false,
                                },
                            },
                            events: {
                                input: _this.rewriteChangeRow,
                            },
                            filter(row) {
                                return _this.$utils.isNotEmpty(row.product_sid);
                            },
                        },
                    },
                    {
                        label: "金额",
                        prop: "amount",
                        align: "center",
                        width: 80,
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 2),
                    },
                    {
                        label: "包装单位",
                        prop: "package_unit",
                        align: "center",
                        width: 80,
                    },
                    {
                        label: "入库数量",
                        prop: "position_in_qty",
                        align: "center",
                        width: 80,
                    },
                    {
                        label: "备注",
                        prop: "note_info",
                        align: "center",
                        editRender: {
                            name: 'CustomInput',
                            filter(row) {
                                return _this.$utils.isNotEmpty(row.product_sid);
                            },
                        },
                    },
                ],
                operates: {
                    fixed: "right",
                    list: [
                        {
                            id: 'add1',
                            size: 'mini',
                            show: true,
                            tooltip: {
                                content: '插入',
                            },
	                        svg: {
		                        iconClass: 'icon-insert',
	                        },
                            filter: (row) => {
                                return _this.isEditFlag;
                            },
                            method: (index, row) => {
                                _this.handleAddRow(row, -1);
                            }
                        },
                        {
                            id: 'add2',
                            size: 'mini',
                            show: true,
                            tooltip: {
                                content: '追加',
                            },
	                        svg: {
		                        iconClass: 'icon-append',
	                        },
                            filter: (row) => {
                                return _this.isEditFlag;
                            },
                            method: (index, row) => {
                                _this.handleAddRow(row, 1);
                            }
                        },
                        {
                            id: 'del',
                            icon: 'fa fa-trash-o',
                            size: 'mini',
                            type: 'danger',
                            show: true,
                            tooltip: {
                                content: '删除',
                            },
                            filter: (row) => {
                                return _this.isEditFlag;
                            },
                            method: (index, row) => {
                                let dataList = _this.dataList.map(item => $.extend({}, item));
                                dataList = dataList.filter(item => item._index !== row._index);
                                _this.dataList = _this.resetIndex(dataList);
                                if (!_this.$utils.isNotEmptyList(dataList)) {
                                    _this.handleAddRow(null, 1);
                                }
                            }
                        }
                    ],
                },
                pagination: false,
            },
            wareHouseList: [],
            oldCode: '',
            onlyPosition: undefined,
            wareHouseProps: {
                remote: _this.$api.API_FindJxcStockWarehouses,
                placeholder: '选择仓库',
                optionProps: {
                    label: 'name',
                    value: 'sid',
                },
            },
        };
    },
    computed: {
        ...mapState('jxc', [ 'inTypeList', 'setting' ]),
        srcRules() {
            let rules = [
                { required: false },
            ];
            if (this.$utils.isNotEmpty(this.formData.in_type) && this.formData.in_type !== 'allocation') {
                rules = [
                    { required: true, message: '请输入数据来源单号', trigger: 'input' },
                ];
            }
            return rules;
        },
        isGenBill() {
            return this.$utils.isNotEmpty(this.formData.src_sid);
        },
        isEditFlag() {
            return !this.detail;
        },
        totalPositionQty() {
            let total = 0;
            this.dataList.forEach(item => {
                if (this.$utils.isNotEmpty(item.position_in_qty)) {
                    total = this.$utils.accAdd(total, item.position_in_qty);
                }
            });
            return total;
        },
    },
    watch: {
        row: {
            handler() {
                this.init();
            },
            deep: true,
            immediate: true,
        },
    },
    methods: {
        async init() {
            let _this = this;
            if (!_this.row) {
                return;
            }
            await _this.storeDispatch('jxc/initSetting');
            if (!_this.detail) {
                _this.onlyPosition = undefined;
                await _this.initOnlyPosition();
            }
            if (_this.$refs.stockInBillForm) {
                _this.$refs.stockInBillForm.clearValidate();
            }
            let sid = _this.$route.query.sid;
            if (_this.$utils.isNotEmpty(_this.row.sid)) {
                sid = _this.row.sid;
            }
            if (_this.$utils.isNotEmpty(sid)) {
                await _this.initData(_this.row.sid);
            } else {
                _this.formData = {
                    in_date: _this.$XEUtils.toDateString(new Date(), 'yyyy-MM-dd'),
                    warehouse_sid: _this.onlyPosition ? _this.onlyPosition.warehouse_sid : null,
                };
                _this.generateCode();
            }
            _this.initTableOptions();
            if (!_this.$utils.isNotEmptyList(_this.dataList)) {
                _this.handleAddRow(null, 1);
            }
        },
        initOnlyPosition() {
            const _this = this;
            return _this.fetchData(_this.$api.API_GetOnlyOnePosition4InOutBill).then(result => {
                _this.onlyPosition = result.data;
            }).catch(() => {
            });
        },
        initTableOptions() {
            let _this = this;
            let columns = _this.tableOptions.baseColumns.map(item => $.extend({}, item));
            columns = clothing.resetTableColumns(_this.setting, columns, 'in_qty', null, row => {
                if (_this.onlyPosition && _this.$utils.isNotEmptyList(row.position_list)) {
                    let position_list = row.position_list.map(item => {
                        let obj = $.extend({}, item);
                        obj.in_qty = row.in_qty;
                        return obj;
                    });
                    _this.$set(row, "position_in_qty", row.in_qty);
                    _this.$set(row, "position_list", position_list);
                }
            });
            columns.forEach(item => {
                if (_this.isGenBill && item.editRender && item.prop !== 'note_info') {
                    delete item.editRender;
                }
            });
            let operates = $.extend({}, _this.tableOptions.operates);
            if (!_this.isEditFlag) {
                columns = columns.map(item => {
                    let obj = $.extend({}, item);
                    delete obj.editRender;
                    return obj;
                });
                operates = {};
            }
            if (_this.isGenBill) {
                operates = {};
            }
            _this.tableOptions = $.extend({}, _this.tableOptions, {
                columns,
                operates,
                getMaxHeight() {
                    let height = $(_this.getActiveTabsContainer()).height();
                    return height * 0.8 - 250;
                },
            });
        },
        initData(sid) {
            let _this = this;
            return _this.fetchData(_this.$api.API_GetJxcStockInbillBySid, {
                sid,
            }).then(result => {
                let resData = result.data || {};
                let dataList = clothing.transferDetailList(_this.setting, resData.item_list, _this.tableOptions.columns);
                if (_this.isEditFlag && _this.onlyPosition) {
                    resData.warehouse_sid = _this.onlyPosition.warehouse_sid;
                }
                _this.formData = resData;
                if (_this.$utils.isNotEmptyList(dataList)) {
                    dataList.forEach(item => {
                        let totalQty = 0;
                        if (clothing.isClothing(_this.setting)) {
                            let presetPositionMap = item.preset_position_map || {};
                            Object.keys(presetPositionMap).forEach(position => {
                                (presetPositionMap[position] || []).forEach(po => {
                                    totalQty = _this.$utils.accAdd(totalQty, po.in_qty);
                                });
                            });
                        } else {
                            (item.position_list || []).forEach(po => {
                                totalQty = _this.$utils.accAdd(totalQty, po.in_qty);
                            });
                        }
                        item.position_in_qty = totalQty;
                    });
                }
                _this.dataList = _this.resetIndex(dataList);
                _this.oldCode = resData.code;
            }).catch(() => {
            });
        },
        generateCode() {
            let _this = this;
            if (_this.$utils.isNotEmpty(_this.oldCode) && _this.oldCode === _this.formData.code) {
                return;
            }
            return _this.storeDispatch('base/getAutoOrderCode', {
                rule_code: 'jxc_in_bill',
            }).then(data => {
                _this.formData = $.extend({}, _this.formData, {
                    code: data,
                });
                _this.oldCode = data;
                if (_this.$refs.stockInBillForm) {
                    _this.$refs.stockInBillForm.clearValidate('code');
                }
            });
        },
        handleClientEvent(event) {
            const _this = this;
            if (!_this.isEditFlag) {
                return;
            }
            if (typeof event.value !== 'undefined' && _this.$utils.isNotEmpty(event.value)) {
                _this.formData = $.extend({}, _this.formData, {
                    client_sid: event.value,
                });
            }
        },
        handleSupplierEvent(event) {
            const _this = this;
            if (!_this.isEditFlag) {
                return;
            }
            if (typeof event.value !== 'undefined' && _this.$utils.isNotEmpty(event.value)) {
                _this.formData = $.extend({}, _this.formData, {
                    supplier_sid: event.value,
                });
            }
        },
        rewriteChangeRow({ row, column }) {
            const _this = this;
            column = Object.assign({}, column, column.params)
            // 手动限制控制数字位数
            if (column.editRender && column.editRender.double) {
                _this.$set(row, column.prop, _this.$XEUtils.DoubleInput(row[column.prop], column.editRender.double));
            }
            if (column.editRender && column.editRender.integer) {
                _this.$set(row, column.prop, _this.$XEUtils.IntInput(row[column.prop]));
            }
            if (column.prop === 'in_qty') {
                if (_this.$utils.isNotEmpty(row.price)) {
                    _this.$set(row, "amount", _this.$utils.accMul(row.in_qty, row.price));
                }
                if (_this.onlyPosition && _this.$utils.isNotEmptyList(row.position_list)) {
                    let position_list = row.position_list.map(item => {
                        let obj = $.extend({}, item);
                        obj.in_qty = row.in_qty;
                        return obj;
                    });
                    _this.$set(row, "position_in_qty", row.in_qty);
                    _this.$set(row, "position_list", position_list);
                }
            }
            if (column.prop === 'price') {
                if (_this.$utils.isNotEmpty(row.in_qty) && _this.$utils.isNotEmpty(row.price)) {
                    _this.$set(row, "amount", _this.$utils.accMul(row.in_qty, row.price));
                }
            }
        },
        handleRemoteSelectEvent(event) {
            const _this = this;
            if (event.type === 'change') {
                _this.dataList.forEach(item => {
                    _this.$set(item, 'warehouse_name', event.data.name);
                    _this.$set(item, 'position_list', []);
                    _this.$set(item, 'position_in_qty', 0);
                });
            }
        },
        handleAddRow(row, state = 1) {
            const _this = this;
            let dataList = _this.dataList.map(item => $.extend({}, item));
            let addData = clothing.genInitData(_this.setting, {
                in_qty: null,
                note_info: null,
            });
            if (row && state <= 0) {
                let index = _this.dataList.findIndex(item => item._index === row._index);
                if (index !== -1) {
                    if (index === 0) {
                        dataList.unshift(addData);
                    } else {
                        dataList.splice(index, 0, addData);
                    }
                } else {
                    dataList.push(addData);
                }
            } else {
                dataList.push(addData);
            }
            _this.dataList = _this.resetIndex(dataList);
        },
        handleGoodsEvent(e, param) {
            const _this = this;
            let { row, column, params } = param;
            if (params.row) {
                _this.$set(row, 'goods_sid', params.row.sid);
                _this.$set(row, 'product_sid', params.row.product_sid);
                _this.$set(row, column.property, params.row.name);
                _this.$set(row, 'note_info', params.row.note_info);
                _this.$set(row, 'package_unit', params.row.unit);
                _this.$set(row, 'price', params.row.product_price);
                if (clothing.isClothing(_this.setting)) {
                    _this.$set(row, 'spec_preset_value', params.row.spec_preset_value);
                    _this.$set(row, 'preset_product_map', params.row.clothing_preset_product_map);
                    _this.$set(row, 'clothing_color_name', params.row.clothing_color_name);
                } else {
                    _this.$set(row, 'spec_name', params.row.spec_name);
                }
                if (_this.$utils.isNotEmpty(row.in_qty) && _this.$utils.isNotEmpty(row.price)) {
                    _this.$set(row, 'amount', _this.$utils.accMul(row.in_qty, row.price));
                }
                if (_this.onlyPosition) {
                    let position_list = [];
                    position_list.push({
                        position_sid: _this.onlyPosition.sid,
                        warehouse_name: _this.onlyPosition.warehouse_name,
                        position_name: _this.onlyPosition.name,
                        price: params.row.product_price,
                        in_qty: 0,
                        position_in_qty: 0,
                        sn: 1,
                    });
                    _this.$set(row, 'position_list', position_list);
                }
            }
        },
        async confirm() {
            const _this = this;
            let valid = await _this.validateForm('stockInBillForm');
            if (!valid) {
                return false;
            }
            if (_this.$utils.isNotEmpty(_this.formData.client_sid) && _this.$utils.isNotEmpty(_this.formData.supplier_sid)){
                _this.$message.error('不能同时选择客户和供应商');
                return false;
            }
            let dataList = _this.dataList.filter(item => _this.$utils.isNotEmpty(item.goods_sid));
            if (!_this.$utils.isNotEmptyList(dataList)) {
                _this.$message.error('订单明细不能为空');
                return false;
            }
            dataList = clothing.procSubData(_this.setting, dataList);
            let subData = $.extend({}, _this.formData);
            subData.item_list = dataList.map(item => {
                let obj = $.extend({}, item);
                obj.package_unit = item.package_unit || item.goods_unit;
                obj.sn = item._index + 1;
                return obj;
            });
            return _this.fetchData(_this.$api.API_SaveJxcStockInbill, subData).then(() => {
                _this.$message.success('保存成功！');
                return true;
            }).catch(() => {
                return false;
            });
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.in_bill_form_container {
    width: 100%;
    height: 100%;
}
</style>
